<?php
/*
 * Author  : top-songshijie
 * Email   : 997031758@qq.com
 * DateTime: 2023/02/22 14:36
 */

namespace SSJ\LaravelHelper\Services\Upload\Strategy;

use OSS\OssClient;
use OSS\Core\OssException;
use SSJ\LaravelHelper\Models\Attachment;
use SSJ\LaravelHelper\Services\Upload\Strategy;

class AliossStrategy extends Strategy
{
    public function handle()
    {
        $attachment = Attachment::check($this->data['md5'], $this->data['sha1']);
        if (lh_isset_not_empty($attachment, 'alioss_preview_path')) {
            return $attachment;
        }

        $this->data['alioss_preview_path'] = $this->upload($this->file, $this->data['path']);

        if ($attachment) {
            $attachment->update(['alioss_preview_path' => $this->data['alioss_preview_path']]);
        } else {
            $attachment = Attachment::query()->create($this->data);
        }

        return $attachment;
    }

    /**
     * 上传到阿里云
     *
     * @param $file
     * @param $filename
     *
     * @return string
     *
     * @throws OssException
     */
    protected function upload($file, $filename)
    {
        $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
        $res       = $ossClient->uploadFile($this->bucket, $filename, $file);

        return $res['oss-request-url'];
    }
}
